package modelo.policia;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class LectorPoliciasXML implements FuenteDePolicias{
	
	private static LectorPoliciasXML instancia= null;
	
	private synchronized static void crearInstancia(){
		if (instancia == null ) {
			instancia = new LectorPoliciasXML();
		}
	}
	public static LectorPoliciasXML obtenerInstancia(){
		if (instancia == null){
			crearInstancia();
		}
		return instancia;
	}
	
	public Document crearArchivoPolicias(File input){
		 Document document = DocumentHelper.createDocument();
		 document.addElement("policias");
	     try{
	    	 XMLWriter output = new XMLWriter(new FileWriter(input));
	    	 output.write(document);
	    	 output.close();
	    	 }
	     catch(IOException e){System.out.println(e.getMessage());}
	     return document;
	}
	public void modificarArchivoPolicias(File input, Document document){
		try{
			XMLWriter output = new XMLWriter(new FileWriter(input));
			output.write(document);
			output.close();
		}
		 catch(IOException e){
			 e.printStackTrace();
        }
	}
	public Document obtenerDocumento(File input) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document documento=null;
		documento = reader.read(input);
		return documento;
	}
	public Element obtenerPolicia(File input, String nombre) throws NoHayPoliciaConEseNombreException, DocumentException{
		Document documento = this.obtenerDocumento(input);
		List<?> list = documento.selectNodes("//policias/Policia");
		Iterator<?> i = list.iterator();
		Element policia = null;
		while(i.hasNext()){
	    	Element element = (Element)i.next();
	    	if (element.getText().toUpperCase().equals(nombre.toUpperCase())) policia=element; 
	    }
		if (policia == null) throw new NoHayPoliciaConEseNombreException();
			else return policia;
	}
	public List<String> obtenerPolicias(File input) throws DocumentException{
		Document documento = this.obtenerDocumento(input);
		List<?> list = documento.selectNodes("//policias/Policia");
		Iterator<?> i = list.iterator();
		List<String> policias = new ArrayList<String>();
		while(i.hasNext()){
	    	Element element = (Element)i.next();
	    	policias.add(element.getText()); 
	    }
		return policias;
	}
}
